<?php

namespace Modules\Activity\Entities;

use Illuminate\Database\Eloquent\Builder;
use Modules\Order\Entities\BaseOrder;

use Modules\Asset\Entities\Package;
use Modules\UI\Entities\Danmu;

use ThrowException;
use Cache;

class ActivityOrder extends BaseOrder
{
    // 代付订单

    protected $guarded = [];
    protected $table = 'orders';

    static public $resourceName = '活动订单';
    static public $orderType = 'activity';

    public $isAutoComplete = true;
    static public $isVisible = false;     // 未付款时是否可见

    static public $autoClosedTimeout = 2;    // 自动关闭时间，默认为30分钟

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('activityOrder', function(Builder $builder) {
            $builder->type('activity');
        });
    }

    public function generateNumber()
    {
        $number = 'A' . date('mdHis') . $this->user_id . rand(100, 999);
        return $number;
    }

    // 支付完成后同步操作
    public function paidListenerSync()
    {
        // 标记为已完成
        // $this->complete();

        // 设置为可见
        $this->update([
            'is_visible' => 1
        ]);

        // 各种活动
        if ($this->node) {
            return $this->node->orderPaidListenerSync($this);
        }

        return true;
    }

    // 创建package
    public function createPackage()
    {
        $cacheKey = 'package_pending_' . $this->uuid;

        // 检测当前订单是否有其它进程在使用
        if (Cache::get($cacheKey)) {
            \Log::error('活动订单的另外一个package创建进程进行中: ' . $this->id);
            return false;
        }

        // 缓存当前正在开奖，缓存时间100s
        Cache::put($cacheKey, 1, 10);

        $order = $this;
        if (Package::where('pay_order_id', $order->id)->first()) {
            // 已创建package，跳过
            return false;
        }

        if ($this->union_status !== 'deliver_pending') {
            return false;
        }

        $activity  = $this->node;

        if (!$activity) {
            return false;
        }

        // 锁定package创建器
        if (!$activity->lockPackageCreator($order)) {
            \Log::error('package创建器锁定中~');

            Cache::forget($cacheKey);
            return false;
        }
        
        // 默认是抽奖活动，创建package
        // 其它活动请在各自的activity派生类内实现此方法（会覆盖这里的实现）
        $package = Package::createWith($order);

        // 创建不了package
        if (!$package) {
            // 关闭订单
            $this->closeAndRefund(6, '活动库存不足', [
                'refund_balance' => $this->pay_money_price
            ]);
            Cache::forget($cacheKey);
            \Log::error('由于活动库存不足关闭订单并自动退款至红包: ' . $this->id);
        }

        // 释放锁
        $activity->releasePackageCreator($order);

        // package创建成功
        if ($package) {
            $activity->packageCreatedListenerSync($order, $package);

            // 订单标记为已完成 
            $this->complete();

            // 创建弹幕
            Danmu::createWithPackage($package);

            return $package;
        }

        Cache::forget($cacheKey);

        return false;
    }

}
